package com.example.softwareengg;




import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.UnderlineSpan;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.content.Intent;


public class Screenout extends HeaderFooter implements OnClickListener   {
	String serverIP=MyOverridenApp.getserverIP();
	static String filename;
    private static final int REQUEST_PICK_FILE = 1;

    private TextView mFilePathTextView;
    private Button mStartActivityButton;
    private File selectedFile;
    

	@Override 
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ViewGroup vg = (ViewGroup) findViewById(R.id.lldata);
        ViewGroup.inflate(Screenout.this, R.layout.screenout, vg);
        mFilePathTextView = (TextView)findViewById(R.id.file_path_text_view);
        mStartActivityButton = (Button)findViewById(R.id.browse);
         
        TextView userName1 = (TextView)findViewById(R.id.textUsername);
		//Intent i1 = getIntent();
		String shruti2 = "Welcome " +MyOverridenApp.getUser();
		
		TextView ResHead = (TextView) findViewById(R.id.reshead);
		
		SpannableString content1 = new SpannableString("Respond");
		SpannableString content2 = new SpannableString(shruti2);
		content1.setSpan(new UnderlineSpan(), 0, content1.length(), 0);
		content2.setSpan(new UnderlineSpan(), 0, content2.length(), 0);
		userName1.setText(content2);
		ResHead.setText(content1);
		 Button upload = (Button)findViewById(R.id.upload);
		 Button home = (Button)findViewById(R.id.home);
		
		
		mStartActivityButton.setOnClickListener(this);
		upload.setOnClickListener(this);
		Button button_logout = (Button) findViewById(R.id.Button_logout);
		
		home.setOnClickListener(this);
		button_logout.setOnClickListener(this);
		
	}
	public void onClick(View v) {
        switch (v.getId()) {
        case R.id.home:
        {
			   Intent intent = new Intent(Screenout.this,ScreenB.class);
			    startActivity(intent);
			    break;

        }

      	        case R.id.browse:
      	        {
      	        	Intent intent = new Intent(this, FilePickerActivity.class);

      	            
      	            startActivityForResult(intent, REQUEST_PICK_FILE);
      	            break;

      	        //ase R.id.You_can_handle_more_onclick_events_from_here:
      	            //Do something
      	            //break;

      	        }
      	        
      	      case R.id.Button_logout:
  	        {
  	        	try{
  	        		Toast.makeText(getApplicationContext(),"Logout", Toast.LENGTH_LONG).show();
  	        		
  	        	Socket client = MyOverridenApp.getClient();
  	        	DataOutputStream outToServer = new DataOutputStream(client.getOutputStream());
  				
  				outToServer.writeBytes("signout\n");
  				client.close();
  				}
  	        	catch(Exception e){
  	        		e.printStackTrace();
  	        		Toast.makeText(getApplicationContext(),"Error Logging out", Toast.LENGTH_LONG).show();
  	        		
  	        	}
  				   Intent intent = new Intent(Screenout.this,ScreenA.class);
  				    startActivity(intent);
  				    break;

  	        }

      	        case R.id.upload:
      	        {
      	        	filename = ((EditText)findViewById(R.id.editupload)).getText().toString();
      	        	try {
						 
						Socket client = MyOverridenApp.getClient();

						DataOutputStream outToServer = new DataOutputStream(client.getOutputStream());
						
						
						BufferedReader inFromServer = new BufferedReader(new InputStreamReader(client.getInputStream()));
						String path  = selectedFile.getAbsolutePath();
					     File f=new File(path);
					     outToServer.writeBytes("upload "+filename.trim()+" "+f.length()+"\n");
							
					     if(f.exists())
					     { 
					    	 //System.out.println("File exists");
					    	 byte buffer[] = new byte[(int)f.length()];
					    	 //System.out.println("File length "+f.length());
					     	BufferedInputStream d=new BufferedInputStream(new FileInputStream(f));
					     	  d.read(buffer,0,buffer.length);
					     	
					     	 OutputStream os = client.getOutputStream();
					     	 //System.out.println("Sending...");
					     	 for(int i=0;i<=buffer.length/1024;i++){
					     		int j=1024;
					     		if(buffer.length-j*(i+1)>0){
					     	 os.write(buffer,j*i,j);
					     	 }
					     		else{
					     			 os.write(buffer,j*i,buffer.length-(j*i));
					     			 break;
					     		}
					     	 
					     	 }
					            os.flush();
					     	 
					  
					     	d.close();
					     	
					     	//System.out.println("File transfered");
					     	 
					     	 //System.out.println("Server reply:");
					     	//String serverReply = inFromServer.readLine();
					     	//System.out.println(serverReply+"\n\n");
					     	//client.close();
					     	
					     	//System.exit(0);
					     	Toast.makeText(getApplicationContext(),"File uploaded!", Toast.LENGTH_LONG).show();
					     	
					     	((EditText)findViewById(R.id.editupload)).setText("");
					     }
						
					 
					} catch (UnknownHostException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Afos.leuto-generated catch block
						e.printStackTrace();
					}
					break;

      	        }

      	    	  
 				    
 				    
        	        default:
            break;
        }


	

	 }
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
        if(resultCode == RESULT_OK) {
            switch(requestCode) {
            case REQUEST_PICK_FILE:
                if(data.hasExtra(FilePickerActivity.EXTRA_FILE_PATH)) {
                    // Get the file path
                    selectedFile = new File(data.getStringExtra(FilePickerActivity.EXTRA_FILE_PATH));
                    // Set the file path text view
                    mFilePathTextView.setText(selectedFile.getAbsolutePath()); 
                    
                    
                    
                   
										    
                    //System.out.println(selectedFile.getPath().toString());
                    //System.out.println(selectedFile.getAbsolutePath().toString());
                    //Now you have your selected file, You can do your additional requirement with file.                
                }
            }
        }
    }
	@Override
	public void onBackPressed() {
	}

}